import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'package:intl/intl.dart';
import 'package:netwrok_log/errorLog/log.dart';
import 'package:x_custom_widget/custom_widget.dart';

class NetworkLogPage extends StatefulWidget {
  const NetworkLogPage({Key? key}) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _NetworkLogPageState createState() => _NetworkLogPageState();
}

class _NetworkLogPageState extends State<NetworkLogPage> {
  List data = [];
  final ScrollController _controller = ScrollController();
  int _page = 0;
  @override
  void initState() {
    super.initState();
    getLogList(0);
    _controller.addListener(() {
      if (_controller.position.maxScrollExtent <= _controller.offset) {
        getLogList(_page++);
      }
    });
  }

  bool isEnd = false;
  getLogList(int page) {
    if (isEnd && page != 0) {
      EasyLoading.dismiss();
      EasyLoading.showSuccess("已加载完毕");
      return;
    }
    EasyLoading.show();
    Log().fetchNetWorkPagedData(page: page).then((value) {
      EasyLoading.dismiss();
      if (value.isEmpty) {
        isEnd = true;

        return;
      } else {
        data = [...data, ...value];
        setState(() {});
      }
    });
  }

  showDetai(Map detailData) {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => NetWorkDetailError(detailData)));
  }

  @override
  Widget build(BuildContext context) {
    if (data.isEmpty) {
      getLogList(0);
    }
    EasyLoading.dismiss();
    return Scaffold(
      appBar: AppBar(
        title: Text("网络请求"),
        actions: [
          GestureDetector(
            child: Icon(Icons.delete),
            onTap: () {
              EasyLoading.show();
              Log().cleanNetWorkLog().then((value) {
                data = [];
                _page = 0;
                isEnd = false;
                setState(() {});
                getLogList(_page);
              });
            },
          )
        ],
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          data = [];
          _page = 0;
          getLogList(_page);
        },
        child: Container(
          color: Colors.black,
          child: ListView.separated(
            controller: _controller,
            itemBuilder: (context, index) {
              String dateStr = DateFormat('yyyy-MM-dd HH:mm:ss').format(
                  DateTime.fromMillisecondsSinceEpoch(data[index]["time"]));
              return GestureDetector(
                onTap: () {
                  showDetai(data[index]);
                },
                child: Container(
                  color: Colors.black,
                  padding: EdgeInsets.all(5),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      CustomText("$index",
                          color: Colors.white,
                          fontSize: 30,
                          fontWeight: FontWeight.w500,
                          padding: EdgeInsets.only(right: 8)),
                      Expanded(
                        child: Container(
                          child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    CustomText(
                                      data[index]["method"],
                                      fontWeight: FontWeight.w500,
                                      color: Color.fromARGB(255, 95, 174, 240),
                                    ),
                                    CustomText("\t\t$dateStr",
                                        fontWeight: FontWeight.w500,
                                        fontSize: 12,
                                        color: Colors.white)
                                  ],
                                ),
                                CustomText(data[index]["url"],
                                    color: Colors.amber, maxLines: 20),
                              ]),
                        ),
                      ),
                      Column(
                        children: [
                          CustomText(
                            "status",
                            color: Colors.white,
                            fontSize: 12,
                          ),
                          CustomText(
                            "${data[index]["status_code"]}",
                            fontSize: 20,
                            fontWeight: FontWeight.w500,
                            color: data[index]["status_code"] == 200
                                ? Colors.green
                                : Colors.red,
                          )
                        ],
                      )
                    ],
                  ),
                ),
              );
            },
            itemCount: data.length,
            separatorBuilder: (BuildContext context, int index) {
              return Divider(
                color: Colors.white,
                height: 0,
              );
            },
          ),
        ),
      ),
    );
  }
}

class NetWorkDetailError extends StatefulWidget {
  const NetWorkDetailError(this.detailData);

  final Map detailData;

  @override
  State<NetWorkDetailError> createState() => _NetWorkDetailErrorState();
}

class _NetWorkDetailErrorState extends State<NetWorkDetailError> {
  @override
  Widget build(BuildContext context) {
    String dateStr = DateFormat('yyyy-MM-dd HH:mm:ss')
        .format(DateTime.fromMillisecondsSinceEpoch(widget.detailData["time"]));
    return Scaffold(
      appBar: AppBar(
        title: Text("网络请求详情"),
        actions: [
          GestureDetector(
            child: Text("复制"),
            onTap: () {
              Clipboard.setData(ClipboardData(
                  text:
                      "${"${widget.detailData["url"]}"}\n${widget.detailData["status_code"]}\n${widget.detailData["request_body"]}\n${widget.detailData["response_body"]}"));
              EasyLoading.showSuccess('文案复制成功～');
            },
          )
        ],
      ),
      body: Container(
        height: MediaQuery.of(context).size.height,
        width: double.infinity,
        color: Colors.black,
        padding: const EdgeInsets.all(12),
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            CustomText(
                              "[ ${widget.detailData["method"]} ]",
                              fontWeight: FontWeight.w900,
                              color: Color.fromARGB(255, 95, 174, 240),
                            ),
                            CustomText("\t\t$dateStr",
                                fontWeight: FontWeight.w500,
                                fontSize: 12,
                                maxLines: 100,
                                color: Colors.white),
                          ],
                        ),
                        CustomText(
                          "${widget.detailData["url"]}",
                          mainAxisAlignment: MainAxisAlignment.start,
                          color: Colors.amber,
                        ),
                      ],
                    ),
                  ),
                  Column(
                    children: [
                      CustomText("status", color: Colors.white, fontSize: 12),
                      CustomText("${widget.detailData["status_code"]}",
                          fontSize: 20,
                          fontWeight: FontWeight.w500,
                          color: widget.detailData["status_code"] == 200
                              ? Colors.green
                              : Colors.red)
                    ],
                  )
                ],
              ),
              Divider(color: Colors.white),
              CustomText("请求参数",
                  fontWeight: FontWeight.w500, color: Colors.white),
              Divider(color: Colors.white),
              ResponseText(data: widget.detailData["request_body"]),
              Divider(color: Colors.white),
              CustomText("响应数据",
                  fontWeight: FontWeight.w500, color: Colors.white),
              Divider(color: Colors.white),
              ResponseText(data: widget.detailData["response_body"]),
              Divider(color: Colors.white),
              CustomText("请求头 ",
                  fontWeight: FontWeight.w500, color: Colors.white),
              Divider(color: Colors.white),
              GestureDetector(
                onLongPress: () {
                  Clipboard.setData(
                      ClipboardData(text: widget.detailData["request_header"]));
                  EasyLoading.showSuccess('复制成功');
                },
                child: CustomText(
                  "${widget.detailData["request_header"]}",
                  maxLines: 11000,
                  color: Colors.white,
                ),
              ),
              Divider(color: Colors.white),
              CustomText("Response Header",
                  fontWeight: FontWeight.w500, color: Colors.white),
              Divider(color: Colors.white),
              CustomText("${widget.detailData["response_header"]}",
                  maxLines: 100, color: Colors.white),
            ],
          ),
        ),
      ),
    );
  }
}

class ResponseText extends StatefulWidget {
  final String data;
  const ResponseText({Key? key, required this.data}) : super(key: key);

  @override
  State<ResponseText> createState() => _ResponseTextState();
}

class _ResponseTextState extends State<ResponseText> {
  bool show = false;
  @override
  Widget build(BuildContext context) {
    if (widget.data == "" || widget.data == "\"\"") {
      return CustomText("无", color: Colors.white);
    }
    String showString = widget.data;
    try {
      final Map<String, dynamic> json = jsonDecode(showString);
      showString = "${fmt(json, 1)}";
    } catch (e) {}
    return GestureDetector(
        onTap: () {
          show = !show;
          setState(() {});
        },
        child: CustomText(showString,
            maxLines: show ? 10000 : 20, color: Colors.white));
  }

  String fmt(dynamic o, int lv, {String sp = ' '}) {
    if (o == null) return '';
    String str = '';

    String pre = sp * lv;

    if (o is Map) {
      str += '{\n';

      for (var item in o.keys) {
        str += pre + '$sp\"$item\":${fmt(o[item], lv + 1)},\n';
      }

      // str = str.replaceRange(str.length - 2, str.length, '\n');

      str += pre + '}';

      return str;
    }
    if (o is String) {
      return '\"$o\"';
    }
    if (o is num) {
      return o.toString();
    }
    if (o is List) {
      str += '[';
      bool isF = true;
      for (var item in o) {
        if (isF) {
          str += '${fmt(item, lv + 1)},\n';
          isF = false;
        } else {
          str += pre + '$sp${fmt(item, lv + 1)},\n';
        }
      }
      // str = str.replaceRange(str.length - 2, str.length, '\n');
      str += pre + ']';
      return str;
    }
    if (o is bool) {
      return o ? 'true' : 'false';
    }
    return '';
  }
}

// ignore: must_be_immutable
